package com.xckj.teacher.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

/**
 * @Author: ChenYao
 * @Describe: 加载图片
 * @Date: 2024/4/11 22:15
 */
public class LoadImageUtil {
    public static boolean isDestroyed(View view) {
        if (view == null || view.getContext() == null) {
            return true;
        }
        Activity activity = findActivity(view.getContext());
        if (activity != null) {
            return activity.isFinishing() || activity.isDestroyed();
        }
        return false;
    }

    public static Activity findActivity(@NonNull Context context) {
        if (context instanceof Activity) {
            return (Activity) context;
        } else if (context instanceof ContextWrapper) {
            return findActivity(((ContextWrapper) context).getBaseContext());
        } else {
            return null;
        }
    }

    @SuppressLint("CheckResult")
    public static void loadImage(String url, ImageView view, int placeHolder) {
        if (isDestroyed(view)) {
            return;
        }
        RequestOptions options = new RequestOptions();
        options.placeholder(placeHolder).error(placeHolder).fallback(placeHolder);
        Glide.with(view).load(url).apply(options).into(view);
    }

    public static void loadImage(Object url, ImageView image) {
        if (isDestroyed(image)) {
            return;
        }
        Glide.with(image).load(url).into(image);
    }
}
